package com.min.log

import com.android.build.api.transform.Format
import com.android.build.api.transform.QualifiedContent
import com.android.build.api.transform.Transform
import com.android.build.api.transform.TransformException
import com.android.build.api.transform.TransformInvocation
import com.android.build.gradle.internal.pipeline.TransformManager
import com.android.utils.FileUtils
import org.gradle.api.Project

class LogTransform extends Transform {

    private Project project

    LogTransform(Project project) {
        this.project = project
    }

    @Override
    String getName() {
        return "log"
    }

    @Override
    Set<QualifiedContent.ContentType> getInputTypes() {
        return TransformManager.CONTENT_CLASS
    }

    @Override
    Set<? super QualifiedContent.Scope> getScopes() {
        return TransformManager.SCOPE_FULL_PROJECT
    }

    @Override
    boolean isIncremental() {
        return true
    }

    @Override
    void transform(TransformInvocation transformInvocation) throws TransformException, InterruptedException, IOException {
        def transformInputs = transformInvocation.inputs
        def outputProvider = transformInvocation.outputProvider
        transformInputs.each {
            transformInput ->
                if (!isIncremental()) {
                    transformInput.jarInputs.each {
                        jar ->
                            // 重命名输出文件（同目录copyFile会冲突）
                            // 必须把每个jar包再次复制到对应的位置，否则在处理class文件时会找不到所有的类
                            String outputFileName = jar.name.replace(".jar", "") + '-' + jar.file.path.hashCode()
                            def output = outputProvider.getContentLocation(outputFileName, jar.contentTypes, jar.scopes, Format.JAR)
                            if (output.exists()) output.delete()
                            FileUtils.copyFile(jar.file, output)
                    }
                }

                transformInput.directoryInputs.each {
                    directory ->
                        new InjectClient().inject(directory.file.absolutePath, project)

                        // 获取output目录
                        def dest = outputProvider.getContentLocation(directory.name,
                                directory.contentTypes, directory.scopes,
                                Format.DIRECTORY)

                        // 将input的目录复制到output指定目录
                        FileUtils.copyDirectory(directory.file, dest)
                }
        }
    }

}
